/*
 * Copyright (C) 2012, EADS France
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 */

package xowl.utils.config;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *
 * @author Laurent WOUTERS
 */
public class Section {
    private String name;
    private Map<String, List<String>> properties;
    
    public String getName() { return name; }
    public boolean isEmpty() { return properties.isEmpty(); }
    
    public Set<String> getProperties() { return properties.keySet(); }
    public List<String> getValues(String property) {
        if (!properties.containsKey(property))
            return new LinkedList<String>();
        return properties.get(property);
    }
    public String getValue(String property) {
        if (!properties.containsKey(property))
            return null;
        List<String> values = properties.get(property);
        if (values.isEmpty())
            return null;
        return values.get(0);
    }
    public void addValue(String property, String value) {
        if (!properties.containsKey(property))
            properties.put(property, new java.util.LinkedList<String>());
        properties.get(property).add(value);
    }
    
    public Section(String name) {
        this.name = name;
        this.properties = new HashMap<String, List<String>>();
    }
    
    public void save(Writer writer) throws IOException {
        List<String> keys = new ArrayList<String>(properties.keySet());
        Collections.sort(keys);
        if (name != null) {
            writer.write("[");
            writer.write(name);
            writer.write("]");
            writer.write(System.lineSeparator());
        }
        for (String option : keys) {
            for (String value : properties.get(option)) {
                writer.write(option + " = " + value + System.lineSeparator());
            }
        }
    }
}
